<template>
  <div>
    <!-- 面包屑导航区 -->
    <el-breadcrumb separator-class="el-icon-arrow-right">
      <el-breadcrumb-item :to="{ path: '/home' }">首页</el-breadcrumb-item>
      <el-breadcrumb-item>权限管理</el-breadcrumb-item>
      <el-breadcrumb-item>角色列表</el-breadcrumb-item>
    </el-breadcrumb>
    <!-- 卡片区域 -->
    <el-card>
      <el-row>
        <el-col>
          <el-button type="primary">添加角色</el-button>
        </el-col>
      </el-row>
      <!-- 角色列表区域 -->
      <el-table :data="rolesList" border stripe>
        <!-- 展开列 -->
        <el-table-column type="expand">
          <template slot-scope="scope">
            <el-row
              v-for="(item1, i1) in scope.row.children"
              :key="item1.id"
              :class="['bdbottom', i1 === 0 ? 'bdtop' : '', 'vccenter']"
            >
              <!-- 一级权限区域 -->
              <el-col :span="5"
                ><el-tag
                  @close="removeRightById(scope.row, item1.id)"
                  closable
                  >{{ item1.authName }}</el-tag
                >
                <i class="el-icon-caret-right"></i
              ></el-col>
              <!-- 二级三级权限区域 -->
              <el-col :span="19">
                <el-row
                  v-for="(item2, i2) in item1.children"
                  :key="item2.id"
                  :class="[i2 === 0 ? '' : 'bdtop', 'vccenter']"
                >
                  <!-- 二级区域 -->
                  <el-col :span="6"
                    ><el-tag
                      type="success"
                      closable
                      @close="removeRightById(scope.row, item2.id)"
                      >{{ item2.authName }}</el-tag
                    >
                    <i class="el-icon-caret-right"></i
                  ></el-col>
                  <!-- 三级区域 -->
                  <el-col :span="18">
                    <el-tag
                      v-for="(item3, i3) in item2.children"
                      :key="item3.id"
                      type="warning"
                      closable
                      @close="removeRightById(scope.row, item3.id)"
                      >{{ item3.authName }}</el-tag
                    >
                  </el-col>
                </el-row>
              </el-col>
            </el-row>
          </template>
        </el-table-column>
        <!-- 索引列 -->
        <el-table-column type="index"> </el-table-column>
        <el-table-column property="roleName" label="角色名称">
        </el-table-column>
        <el-table-column property="roleDesc" label="角色描述">
        </el-table-column>
        <el-table-column label="操作" width="300px">
          <template slot-scope="scope">
            <el-button type="primary" icon="el-icon-edit" size="mini"
              >编辑</el-button
            >
            <el-button type="danger" icon="el-icon-delete" size="mini"
              >删除</el-button
            >
            <el-button
              type="warning"
              icon="el-icon-setting"
              size="mini"
              @click="showSetRightDialog(scope.row)"
              >分配权限</el-button
            >
          </template>
        </el-table-column>
      </el-table>
    </el-card>
    <!-- 分配权限对话框 -->
    <el-dialog
      title="提示"
      :visible.sync="SetRightDialogVisiable"
      width="50%"
      :before-close="handleClose"
      @close="clearTree"
    >
      <!-- 树形控件区域 -->
      <el-tree
        :data="rightsList"
        :props="treeProps"
        show-checkbox
        default-expand-all
        node-key="id"
        :default-checked-keys="defaultKeys"
        ref="tree"
      ></el-tree>
      <span slot="footer" class="dialog-footer">
        <el-button @click="SetRightDialogVisiable = false">取 消</el-button>
        <el-button type="primary" @click="allotRight">确 定</el-button>
      </span>
    </el-dialog>
  </div>
</template>
<script>
export default {
  data() {
    return {
      //   角色列表数据
      rolesList: [],
      // 权限列表数据
      rightsList: [],
      // 控制分配权限对话框的显示与隐藏
      SetRightDialogVisiable: false,
      // 树形控件默认选择id数据
      defaultKeys: [],
      // 分配权限的角色id
      roleId: '',
      // 树形控件渲染数据
      treeProps: {
        children: 'children',
        label: 'authName'
      }
    }
  },
  created() {
    //   获取角色列表数据
    this.getRolesList()
  },
  methods: {
    // 获取角色列表数据函数
    async getRolesList() {
      const { data: res } = await this.$http.get('roles')
      if (res.meta.status !== 200) {
        return this.$message.error('获取角色列表失败！')
      }
      this.rolesList = res.data
      console.log(this.rolesList);
    },
    // 根据id删除权限函数
    async removeRightById(role, rightId) {
      const confirmResult = await this.$confirm('此操作将永久删除该权限, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).catch(err => err)
      if (confirmResult !== 'confirm')
        return this.$message.info('已取消删除')
      // console.log('确定删除');
      const { data: res } = await this.$http.delete(`roles/${role.id}/rights/${rightId}`)
      if (res.meta.status !== 200) {
        return this.$message.error('删除权限失败！')
      }
      this.$message.success('删除权限成功！')
      role.children = res.data
    },
    // 展示分配权限对话框函数
    async showSetRightDialog(role) {
      // 将当前角色id保存到data中
      this.roleId = role.id
      // 将权限列表数据保存到data里面
      const { data: res } = await this.$http.get('rights/tree')
      if (res.meta.status !== 200)
        return this.$message.error('获取用户权限失败！')
      this.rightsList = res.data
      console.log(this.rightsList);
      // 获取三级节点的id
      this.getTreeKeys(role, this.defaultKeys)
      this.SetRightDialogVisiable = true
    },
    // 通过递归的形式把三级节点的id值存储到数组中
    getTreeKeys(node, arr) {
      if (!node.children) {
        return arr.push(node.id)
      }
      node.children.forEach(item => {
        this.getTreeKeys(item, arr)
      });

    },
    // 关闭对话框时把当前角色下的三级分类数据清空
    clearTree() {
      this.defaultKeys = []
    },
    // 分配权限对话框点击确定处理函数
    async allotRight() {
      const arrid = [...this.$refs.tree.getCheckedKeys(), ...this.$refs.tree.getHalfCheckedKeys()]
      const strid = arrid.join(',')
      const { data: res } = await this.$http.post(`roles/${this.roleId}/rights`, { rids: strid })
      if (res.meta.status !== 200)
        return this.$message.error('角色授权失败！')
      this.getRolesList()
      this.SetRightDialogVisiable = false
      this.$message.success('角色授权成功！')


    }


  }


}
</script>
<style lang="less" scoped>
.el-tag {
  margin: 7px;
}
.bdtop {
  border-top: 1px solid rgb(206, 204, 204);
}
.bdbottom {
  border-bottom: 1px solid rgb(206, 204, 204);
}
.vccenter {
  display: flex;
  align-items: center;
}
</style>